package jdbc_code;

import java.sql.*;

/*
    查询数据
 */
public class jdbcDemo5 {

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet result = null;
        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接对象
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC", "root", "qwe123");
            //3.定义sql
            String sql = "select * from student";
            //第四步和第五步结合一起写(链式编程) int i = conn.createStatement().executeUpdate(sql);
            //4.获取执行sql对象
            stmt = conn.createStatement();
            //5.执行sql语句
            result = stmt.executeQuery(sql);
            //6.处理结果
            //6.1 让游标向下移动一行
            result.next();
            //6.2获取数据
            int id = result.getInt(1);
            String name = result.getString("name");
            int age = result.getInt(3);

            System.out.println(id + "---" + name + "---" + age);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //7.释放资源
            try {
                if (result != null) {
                    result.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (stmt != null) {
                    stmt.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }

            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
